package com.cherry.androidcode.jetpack.databinding

import android.graphics.drawable.Drawable
import android.net.Uri
import android.text.TextUtils
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.databinding.BindingAdapter
import com.cherry.androidcode.R
import com.cherry.androidcode.image.GlideApp
import com.parkingwang.android.SwResource

/**
 * @author Cherry(dongmiansheng@gmail.com)
 * @since 2021/6/5
 */

object ImageHandle {

    @JvmStatic
    @BindingAdapter("img_uri", "default_place", "error_place")
    fun uriImg(
        imageView: ImageView,
        url: Uri?,
        @DrawableRes defaultPlace: Int?,
        @DrawableRes errorPlace: Int?
    ) {
        if (url != null) {
            GlideApp.with(imageView.context)
                .load(url).placeholder(defaultPlace ?: R.mipmap.ic_launcher).into(imageView)
        } else {
            imageView.setBackgroundResource(errorPlace ?: R.mipmap.ic_launcher)
        }
    }


    @JvmStatic
    @BindingAdapter("img_network")
    fun networkImg(imageView: ImageView, url: String?) {
        if (!TextUtils.isEmpty(url)) {
            GlideApp.with(imageView.context)
                .load(url).placeholder(R.mipmap.ic_launcher).into(imageView)
        } else {
            imageView.setBackgroundResource(R.color.colorPrimaryDark)
        }
    }

    @JvmStatic
    @BindingAdapter("img_network_default", "error_place", requireAll = false)
    fun networkImgDefaultPlace(imageView: ImageView, url: String?, errorPlace: Drawable?) {
        GlideApp.with(imageView.context)
            .load(url).placeholder(errorPlace ?: SwResource.getDrawable(R.mipmap.ic_launcher))
            .into(imageView)
    }


}